package com.hy.server.report;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

public class poi_excel {

    public static void main(String[] args) throws IOException {
        //工作
        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet名称");
        //单元格样式
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //创建行
        Row row0 = sheet.createRow(0);
        Row row1 = sheet.createRow(1);
        //标题 合并单元格
        Cell title = row0.createCell(0);
        title.setCellValue("随机数");
        title.setCellStyle(cellStyle);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));

        Cell cell0 = row1.createCell(0);
        Cell cell1 = row1.createCell(1);
        Cell cell2 = row1.createCell(2);
        //写入
        cell0.setCellValue("列1");
        cell1.setCellValue("列2");
        cell2.setCellValue("列3");
        Random random = new Random();
        for (int i = 2; i < 10; i++) {
            Row row = sheet.createRow(i);
            row.createCell(0).setCellValue(random.nextInt(999));
            row.createCell(1).setCellValue(random.nextInt(999));
            row.createCell(2).setCellValue(random.nextInt(999));
        }
        System.out.println(System.getProperty("user.dir"));
        save(workbook, "F:\\temp\\test.xlsx", true);
    }

    public static void save(Workbook workbook, String path, boolean cover) throws IOException {
        if (workbook == null || path == null) {
            return;
        }
        File file = new File(path);
        if (file.exists()) {
            if (cover) {
                file.delete();
            } else {
                throw new IOException("file (" + path + ")  already exists");
            }
        } else {
            file.getParentFile().mkdirs();
        }
        try (FileOutputStream fos = new FileOutputStream(file)) {
            workbook.write(fos);
        }
    }

}
